<script setup lang="ts">
import { GetCodeDataAPI, PostloginCodeAPI } from '@/api/common'
import { useUserStore } from '@/store'
import type { postloginCodeParams } from '@/types/common'
import { ref } from 'vue'

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})


const FormData = ref<postloginCodeParams>({
  mobile: "13230000061",
  code:'123456'
})

const FormRules = ref<UniHelper.UniFormsRules>({
  mobile: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern:/^1[3-9]\d{9}$/,errorMessage:'请输入正确的的手机号'}
    ]
},
  code: {
    rules: [
      { required: true, errorMessage: '请输入验证码' },
      { pattern:/^\d{6}$/,errorMessage:'验证码格式错误'}
    ]
  }
})

const formRef = ref<UniHelper.UniFormsInstance>()
const isAgree = ref(false)
const store = useUserStore()

const handlerSubmit = async () => {
  if (!isAgree.value) {
    return uni.showToast({ title: '请同意用户协议和隐私协议', icon: 'none' })
  }
  await formRef.value?.validate?.()
  const res = await PostloginCodeAPI(FormData.value)
  console.log(res);
  store.setToken(res.data.token)
  uni.showToast({ title: '登录成功', icon: 'success' })
  uni.switchTab({
    url:"/pages/index/index"
  })
}

// 倒计时处理
const showCountDown = ref(false)
const getMobileCode = async () => {
  try {
    await formRef.value?.validateField?.(['mobile'])
    showCountDown.value = true
    const res = await GetCodeDataAPI({ mobile: FormData.value.mobile, type: 'login' })
    console.log(res);
    
  } catch {
    
  }
}
</script>

<template>
  <uni-forms class="login-form" ref="formRef" :model="FormData" :rules="FormRules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        v-model="FormData.mobile"
        :maxlength="11"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="code">
      <uni-easyinput
        v-model="FormData.code"
        :maxlength="6"
        :input-border="false"
        :clearable="false"
        placeholder="请输入验证码"
        placeholder-style="color: #C3C3C5"
      />
      <text class="text-button" @click="getMobileCode" v-if="!showCountDown">获取验证码</text>
      <view class="text-button" v-else>
        <uni-countdown
          :show-day="false"
          :show-hour="false"
          :show-minute="false"
          :second="5"
          @timeup="showCountDown = false"
        ></uni-countdown>
        秒后重新发送
      </view>
      
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>
    {{ FormData }}
    {{ isAgree }}
    <button class="uni-button" @tap="handlerSubmit">登 录</button>
  </uni-forms>
</template>

<style lang="scss">
@import '../styles.scss';
</style>
